import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { Role } from '../role/role.entity'
import { ROLES_KEY } from '../decorators/roles.decorator'
import { UserService } from '../user/user.service'
import { RoleEnum } from '../enum/role.enum'
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private userService: UserService,
    private reflector: Reflector
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [context.getHandler(), context.getClass()])
    if (!requiredRoles) {
      return true
    }
    const req = context.switchToHttp().getRequest()
    const user = await this.userService.findByUsername(req.user.username)

    const roles = user.roles.map((o) => o.role)
    return roles.includes(RoleEnum.Admin) || requiredRoles.some((role) => roles.includes(<RoleEnum>role))
  }
}
